﻿using System.Collections.Generic;
using System.Linq;
using Identity;
using Microsoft.AspNetCore.Identity;
using Ornament.ImportHelper;
using Text.Helper;

namespace Fee.IO.Importers
{
    public class VendorImporter<T> : BaseImporter<T> where T : FeeDbContext
    {
        private readonly UserManager<User> _userManager;

        public VendorImporter(T context, UserManager<User> userManager) : base(context, true)
        {
            _userManager = userManager;
        }

        protected override bool ConverTo(IList<string> rowStringInfo, out ImportResultItem item)
        {
            //名称 联系人 联系电话 地址  发票抬头 纳税人识别号  开户行 账号
            item = new ImportResultItem();
            var company = rowStringInfo.ImportString(0, "名称", item, true);

            var vendor = Context.Vendors.FirstOrDefault(f => f.Name == company) ?? new Vendor();

            if (vendor.Id == 0) vendor.Name = company;

            vendor.Contact = rowStringInfo.ImportString(1, "联系人", item, false);
            vendor.ContactPhone = rowStringInfo.ImportString(2, "联系电话", item, false);
            vendor.Address = rowStringInfo.ImportString(3, "地址", item, false);
            vendor.FullName = rowStringInfo.ImportString(4, "发票抬头", item, false);
            vendor.TaxNumber = rowStringInfo.ImportString(5, "纳税人识别号", item, false);
            vendor.Bank = rowStringInfo.ImportString(6, "开户行", item, false);
            vendor.BankAccount = rowStringInfo.ImportString(7, "账号", item, false);
            //自动创建账号
            var accountName = PinYinHelper.ToPinYin(vendor.Name);


            if (!item.HasError)
            {
                item.Data.Add(vendor);
                var user = _userManager.FindByNameAsync(accountName).Result;

                if (user == null)
                {
                    user = new User
                    {
                        Name = vendor.Name,
                        UserName = accountName,
                        PhoneNumber = vendor.ContactPhone
                    };
                    var createUserError = _userManager.CreateAsync(user, "Pass!23").Result;
                    if (!createUserError.Succeeded) item.AddError(0, accountName + "创建账号失败");
                }

                user.Vendor = vendor;


                return true;
            }

            return false;
        }
    }
}